package cn.edu.gdu.quizpractice.service.impl;

import cn.edu.gdu.quizpractice.dao.ChoiceQuestionDao;
import cn.edu.gdu.quizpractice.entity.ApiResult;
import cn.edu.gdu.quizpractice.entity.ChoiceQuestion;
import cn.edu.gdu.quizpractice.common.exception.ExcelImportException;
import cn.edu.gdu.quizpractice.service.ExcelImportService;
import cn.edu.gdu.quizpractice.common.utils.ChoiceQuestionExcelListener;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * @Author: Aubery
 * @Date: 2025-03-22-11:11
 * @Description:
 */
@Service
@Slf4j
public class ExcelImportServiceImpl implements ExcelImportService {

    @Autowired
    private ChoiceQuestionDao choiceQuestionDao;

    @Override
    @Async
    public CompletableFuture<ApiResult<String>> importExcelAsync(MultipartFile file) {
        log.info("开始处理文件: {}", file.getOriginalFilename());
        try {
            // 使用临时文件避免流关闭问题
            java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("excel-", ".xlsx");
            file.transferTo(tempFile);

            EasyExcel.read(tempFile.toFile(), ChoiceQuestion.class,
                            new ChoiceQuestionExcelListener(choiceQuestionDao))
                    .sheet()
                    .doRead();

            return CompletableFuture.completedFuture(ApiResult.success("导入成功"));
        } catch (IOException | ExcelImportException e) {
            return CompletableFuture.completedFuture(ApiResult.fail(e.getMessage()));
        } catch (Exception e) {
            return CompletableFuture.completedFuture(ApiResult.fail("系统异常: " + e.getMessage()));
        }
    }
}
